package com.exam.examtest.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.blankj.utilcode.util.PermissionUtils
import com.exam.examtest.R
import com.gyf.barlibrary.ImmersionBar
import java.lang.ref.WeakReference
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.view.KeyEvent
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.PermissionUtils.isGranted
import com.tbruyelle.rxpermissions2.RxPermissions


/**
 * 闪屏页面
 */
@Suppress("DEPRECATION")
class SplashActivity : BaseActivity() {

    var mCountDownText: TextView? = null
    private var mTimerCount: TimeCount? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ImmersionBar.with(this)
            .fitsSystemWindows(true)
            .statusBarColor(R.color.white)
            .statusBarDarkFont(true)
            .init()

        initView()
        rxRequestPermissions(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            describe = "存储"
        ) {
            mTimerCount = TimeCount(this, 5000, 1000)
            //开启倒计时
            mTimerCount?.start()
        }
    }

    /**
     * 初始化View
     */
    private fun initView() {
        //倒计时
        mCountDownText = TextView(this)
        val skipButtonLayoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        skipButtonLayoutParams.gravity = Gravity.TOP or Gravity.END
        val skipButtonMarginT = dip2Px(this, 30)
        val skipButtonMarginR = dip2Px(this, 20)
        skipButtonLayoutParams.setMargins(0, skipButtonMarginT, skipButtonMarginR, 0)
        mCountDownText?.layoutParams = skipButtonLayoutParams
        val skipButtonPaddingTB = dip2Px(this, 5)
        val skipButtonPaddingLR = dip2Px(this, 18)
        mCountDownText?.setPadding(
            skipButtonPaddingLR,
            skipButtonPaddingTB,
            skipButtonPaddingLR,
            skipButtonPaddingTB
        )
        mCountDownText?.setBackgroundResource(R.drawable.shape_edge_e0b65_20_bg)
        mCountDownText?.gravity = Gravity.CENTER
        mCountDownText?.setTextColor(resources.getColor(R.color.color_333333))
        mCountDownText?.textSize = 12f
        addContentView(mCountDownText, skipButtonLayoutParams)

        //中间Welcome字样
        val mCenterText = TextView(this)
        val centerTextLayoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        centerTextLayoutParams.gravity = Gravity.CENTER
        mCenterText.text = resources.getText(R.string.welcome_text)
        mCenterText.textSize = 40f
        mCenterText.setTextColor(resources.getColor(R.color.color_333333))
        addContentView(mCenterText, centerTextLayoutParams)
    }

    /**
     * 倒计时
     */
    private inner class TimeCount internal constructor(
        activity: SplashActivity,
        millisInFuture: Long,
        countDownInterval: Long

    ) : CountDownTimer(millisInFuture, countDownInterval) {

        private val mRef: WeakReference<SplashActivity>

        init {
            mRef = WeakReference(activity)
        }

        @SuppressLint("SetTextI18n")
        override fun onTick(millisUntilFinished: Long) {
            val activity = mRef.get()
            if (activity != null) {
                if (millisUntilFinished / 1000 > 0) {
                    activity.mCountDownText?.text =
                        (millisUntilFinished / 1000).toString() + "s"//设置倒计时时间
                } else {
                    skip()
                }
            }
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish() {
            val activity = mRef.get()
            if (activity != null) {
                //activity.mCountDownText?.text = "0" + "s"//设置倒计时时间
                //skip()
            }
        }
    }

    /**
     * 跳转操作
     */
    fun skip() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    /**
     *  传入权限与权限描述，在需要权限的功能打开之前调用，vararg代表的是可变参数
     */
    private fun rxRequestPermissions(
        vararg permissions: String,
        describe: String,
        onGranted: () -> Unit
    ) {//onGranted是回调
        val keyListener = DialogInterface.OnKeyListener { _, keyCode, event ->
            keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0
        }
        //有一项权限用户不允许的话就进入到这里对话框
        val dialog = AlertDialog.Builder(this)
            .setTitle("权限申请")
            .setMessage("${describe}为必选项，开通后方可正常使用APP,请在设置中开启。")
            .setOnKeyListener(keyListener)
            .setCancelable(false)
            .setNegativeButton("退出") { _, _ ->
                showShortToast("${describe}权限未开启，不能正常使用哦~")
                finish()
            }
            .create()
        val rxPermissions = RxPermissions(this)
        //传递kotlin的可变长参数给Java的可变参数的时候需要使用修饰符 * ；这个修饰符叫做Speread Operator
        // 它只支持展开的Array 数组，不支持List集合，它只用于变长参数列表的实参，不能重载，它也不是运算符；
        rxPermissions.request(*permissions)
            .subscribe { granted ->
                if (granted) {
                    onGranted()
                } else {
                    dialog.show()
                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        //倒计时取消
        mTimerCount?.cancel()
    }
}
